import Fdfs_client as Fdfs_client
from django.conf import settings
from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client

class FDFSStorage(Storage):
    def ___init__(self,client_conf=None, base_url=None):
        if client_conf is None:
            client_conf = settings.FDFS_CLIENT_CONF
            self.client_conf = client_conf

        if base_url is None:
            base_url = settings.FDFS_URL

        self.base_url = base_url

    def _save(self, name ,content):
        client = Fdfs_client(self.client_conf)
        res = client.upload_by_buffer(content.read())

        if res.get('Status') != 'Upload successd.':
            raise Exception('上传文件到FDFS系统失败')
        file_id = res.get("Remote file_id")

        return file_id

    def exists(self, name):
        return False

    def url(self, name):
        return self.base_url + name